<template>
  <div class="page-container">
    <div class="page-card-container">
      <a-form class="mb-20" :model="pageSet" layout="inline">
        <a-form-item label="模板名称">
          <a-input v-model:value="pageSet.searchKey" allowClear></a-input>
        </a-form-item>
        <a-form-item>
          <div class="flex-row-ycenter">
            <div class="commonBtn-primary mr-10" @click="loadPagination(true)">
              搜索
            </div>
            <div class="commonBtn-primary mr-10" @click="goHandle(1)">新增</div>
          </div>
        </a-form-item>
      </a-form>
      <a-table
        size="small"
        :loading="tableLoading"
        :dataSource="tableData"
        :columns="columns"
        bordered
        :pagination="false"
      >
        <template #bodyCell="{text, record, index, column}">
          <div
            class="flex-row-xy-center c-primaryColor fs-12"
            v-if="column.dataIndex == 'handle'"
          >
            <!-- v-btn-permission="'approveFlow:updata'" -->
            <spand class="mr-10 pointer" @click="goHandle(2, record)"
              >编辑</spand
            >
            <!-- v-btn-permission="'approveFlow:dele'" -->
            <span class="pointer" @click="goHandle(3, record, index)"
              >删除</span
            >
          </div>
        </template>
      </a-table>
      <Pagination
        class="mt-10"
        :page-set="pageSet"
        :load-pagination="loadPagination"
      ></Pagination>
      <a-drawer width="80%" v-model:open="showModal" :title="handleTitle">
        <a-steps :current="stepsKey">
          <a-step key="基础信息设置" title="基础信息设置"></a-step>
          <a-step
            key="流程字段设置"
            title="流程字段设置"
            v-if="form.designType !== 0"
          ></a-step>
          <a-step key="审批流程设置" title="审批流程设置"></a-step>
        </a-steps>
        <a-form
          class="mt-20"
          :model="form"
          ref="formRef"
          :label-col="{span: 6}"
        >
          <div class="box-center" style="width: 50%" v-show="stepsKey === 0">
            <a-form-item
              label="模板类型"
              name="designType"
              :rules="[{required: true, message: '请选择模板类型'}]"
            >
              <a-select
                v-model:value="form.designType"
                placeholder="请选择模板类型"
                disabled
              >
                <a-select-option
                  v-for="(item, index) in designTypeList"
                  :key="index"
                  :value="item.value"
                  >{{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              label="模板名称"
              name="name"
              :rules="[{required: true, message: '请填写模板名称'}]"
            >
              <a-input
                v-model:value="form.name"
                placeholder="请填写模板名称"
              ></a-input>
            </a-form-item>
            <a-form-item
              label="是否启用"
              name="isEnable"
              :rules="[
                {required: true, message: '请选择是否启用', type: 'boolean'}
              ]"
            >
              <a-switch v-model:checked="form.isEnable" />
            </a-form-item>
            <a-form-item label="流程使用范围">
              <div
                class=""
                style="
                  border: 1px solid orange;
                  padding: 10px;
                  border-radius: 4px;
                "
              >
                <div class="commonBtn-primary" @click="addOrChangeUser">
                  添加/修改成员(不选择表示全员可用)
                </div>
                <div
                  v-if="arrToString(permission, 'name') !== '请选择'"
                  class="mt-10"
                >
                  {{ arrToString(permission, "name") }}
                </div>
              </div>
            </a-form-item>
          </div>
        </a-form>
        <div
          style="height: 700px"
          v-show="stepsKey === 1 && form.designType !== 0"
        >
          <DynamicForm
            v-model:data="formContent"
            ref="DynamicFormRef"
          ></DynamicForm>
        </div>
        <!-- <div style="height: 700px;overflow-y: auto;" v-show="stepsKey === 2 || (form.designType === 0 && stepsKey === 1)">
          <FlowNode v-model:node="designContent"></FlowNode>
        </div> -->
        <div
          style="display: flex; justify-content: end"
          v-show="stepsKey === 2 || (form.designType === 0 && stepsKey === 1)"
        >
          <!-- <a-button @click="printOpen">打印审批流程</a-button> -->
        </div>
        <div
          style="height: 685px; overflow-y: auto; background-color: #f1f1f1"
          v-show="stepsKey === 2 || (form.designType === 0 && stepsKey === 1)"
        >
          <div class="print" style="min-width: 1000px">
            <FlowNode v-model:node="designContent"></FlowNode>
          </div>
        </div>

        <template #footer>
          <div class="flex-row-xy-center">
            <a-button class="mr-20" @click="showModal = false">取消</a-button>
            <a-button
              class="mr-20"
              type="primary"
              @click="prev"
              v-if="stepsKey > 0"
              >上一步</a-button
            >
            <a-button
              class="mr-20"
              type="primary"
              @click="next"
              v-if="
                (stepsKey !== 2 && form.designType !== 0) ||
                (stepsKey !== 1 && form.designType === 0)
              "
              >下一步
            </a-button>
            <a-button
              type="primary"
              v-if="stepsKey === 2 || (form.designType === 0 && stepsKey === 1)"
              @click="showModalCon"
              >提交
            </a-button>
          </div>
        </template>
      </a-drawer>
    </div>

    <QuickUser
      :type="[1, 2, 3]"
      v-if="showQuickUser"
      v-model:show="showQuickUser"
      v-model:user-select="userSelect"
      v-model:role-select="roleSelect"
      v-model:org-select="orgSelect"
      :orgSelectList="orgSelectList"
      :roleSelectList="roleSelectList"
      :userSelectList="userSelectList"
      @ok="showQuickUserCon"
    ></QuickUser>
    <!-- <PrintSetting ref="PrintSettingRef" selector=".print"></PrintSetting> -->
  </div>
</template>
<script setup lang="ts">
import {ref, provide} from "vue";
import {
  flowdesignAdd,
  flowdesignDelete,
  flowdesignDetail,
  flowdesignPage,
  flowdesignEdit
} from "@/api/configCenter/platform/processTemplate";
import useAppStore from "@/store/app";
// import PrintSetting from "@/components/approve/PrintSetting.vue";
import {Modal} from "ant-design-vue";
import Pagination from "@/components/pagination/Pagination.vue";
import DynamicForm from "@/components/dynamicForm/DynamicForm.vue";
import QuickUser from "@/components/quick/QuickUser.vue";
import FlowNode from "@/components/flow/FlowNode.vue";
import {getCodeName} from "@/utils/common";
//请求参数
const pageSet: any = ref({
  pageNo: 1,
  pageSize: 20,
  total: 0
});
const PrintSettingRef = ref();
const printOpen = () => {
  PrintSettingRef.value.showPrintSettingCon();
};
const tableData = ref([]); //表格数据
const tableLoading = ref(false); //表格加载
const form: any = ref({}); //表单数据
const formRef = ref(); //表单ref
const stepsKey = ref<number>(0);
const designContent = ref({});
const permission = ref([]);
const formContent = ref({
  formConfig: {},
  formList: []
});

const designTypeList = ref([
  {
    value: 0,
    label: "通用类型"
  }
  // {
  //   value: 1,
  //   label: "考勤管理"
  // },
  // {
  //   value: 2,
  //   label: "财务管理"
  // },
  // {
  //   value: 3,
  //   label: "行政管理"
  // },
  // {
  //   value: 4,
  //   label: "用车申请"
  // },
  // {
  //   value: 5,
  //   label: "CA锁管理"
  // }
]);

const arrToString = (arr: object[], key: string) => {
  if (arr.length) return arr.map((item) => item[key]).join(",");
  return "请选择";
};
/**
 * 获取表格数据
 * @param reset 是否重置
 */
const loadPagination = (reset: boolean = false) => {
  tableLoading.value = true;
  if (reset) {
    tableData.value = [];
    pageSet.value.pageNo = 1;
  }

  flowdesignPage(pageSet.value)
    .then((res) => {
      tableData.value = res.data.rows;
      pageSet.value.total = res.data.totalRows;
      tableLoading.value = false;
    })
    .catch(() => {
      tableLoading.value = false;
    });
};
loadPagination();
const orgSelect = ref([]);
const orgSelectList = ref([]);
const userSelectList = ref([]);
const roleSelectList = ref([]);
const userSelect = ref([]);
const roleSelect = ref([]);
const showQuickUser = ref(false);
const addOrChangeUser = () => {
  orgSelectList.value = permission.value.filter((item: any) => item.type === 1);
  userSelectList.value = permission.value.filter(
    (item: any) => item.type === 2
  );
  roleSelectList.value = permission.value.filter(
    (item: any) => item.type === 3
  );
  orgSelect.value = permission.value
    .filter((item: any) => item.type === 1)
    .map((item: any) => item.id);
  userSelect.value = permission.value
    .filter((item: any) => item.type === 2)
    .map((item: any) => item.id);
  roleSelect.value = permission.value
    .filter((item: any) => item.type === 3)
    .map((item: any) => item.id);
  showQuickUser.value = true;
};
const showQuickUserCon = (e) => {
  let {user, org, role} = e;
  let orgNew = org.map((item) => {
    return {
      type: 1,
      id: item.id,
      name: item.title
    };
  });
  let userNew = user.map((item) => {
    return {
      type: 2,
      id: item.id,
      name: item.name
    };
  });
  let roleNew = role.map((item) => {
    return {
      type: 3,
      id: item.id,
      name: item.name
    };
  });
  permission.value = [...orgNew, ...userNew, ...roleNew];
};

const resetData = () => {
  form.value = {};
  form.value.isEnable = true;
  designContent.value = {};
  formContent.value = {
    formConfig: {},
    formList: []
  };
  permission.value = [];
  stepsKey.value = 0;
};
// 把字段数据传给字段限制FlowCard组件里
provide("formContentProvide", formContent);

const showModal = ref(false);
const handleTitle = ref<string>();
const handleType = ref<number>();
const goHandle = (type: number, info?: any, index?: number) => {
  handleType.value = type;
  resetData();
  if (formRef.value) {
    //重置验证
    formRef.value.clearValidate();
  }
  if (type === 1) {
    handleTitle.value = "新增";
    showModal.value = true;
    form.value.designType = 0;
    return;
  }
  if (type === 2) {
    handleTitle.value = "编辑";
    useAppStore.loading = true;
    flowdesignDetail({id: info.id}).then((res) => {
      permission.value = JSON.parse(res.data.permission);
      designContent.value = JSON.parse(res.data.designContent);
      formContent.value = JSON.parse(res.data.formContent);

      form.value = res.data;
      showModal.value = true;
      useAppStore.loading = false;
    });
    return;
  }
  if (type === 3) {
    Modal.confirm({
      title: "提示",
      content: "确定要删除吗",
      onOk() {
        useAppStore.loading = true;
        flowdesignDelete({id: info.id}).then(() => {
          tableData.value.splice(index, 1);
          pageSet.value.total--;
          useAppStore.loading = false;
        });
      }
    });
    return;
  }
};

const DynamicFormRef = ref();

const next = () => {
  if (stepsKey.value === 0) {
    formRef.value.validate().then(() => {
      stepsKey.value++;
    });
    return false;
  }
  if (stepsKey.value === 1) {
    if (DynamicFormRef.value.validate()) {
      stepsKey.value++;
      return false;
    }
  }
};

const prev = () => {
  stepsKey.value--;
};

const showModalCon = () => {
  if (handleType.value === 1) {
    formRef.value.validate().then(() => {
      useAppStore.loading = true;
      form.value.permission = JSON.stringify(permission.value);
      form.value.designContent = JSON.stringify(designContent.value);
      form.value.formContent = JSON.stringify(formContent.value);
      flowdesignAdd(form.value).then(() => {
        loadPagination();
        showModal.value = false;
        useAppStore.loading = false;
      });
    });
  }

  if (handleType.value === 2) {
    formRef.value.validate().then(() => {
      useAppStore.loading = true;
      form.value.permission = JSON.stringify(permission.value);
      form.value.designContent = JSON.stringify(designContent.value);
      form.value.formContent = JSON.stringify(formContent.value);
      flowdesignEdit(form.value).then(() => {
        loadPagination();
        showModal.value = false;
        useAppStore.loading = false;
      });
    });
  }
};

const columns = [
  {
    title: "序号",
    dataIndex: "name",
    align: "center",
    customRender: function ({index}) {
      return index + 1;
    },
    width: 80
  },
  {
    title: "模板类型",
    dataIndex: "designType",
    align: "center",
    customRender: ({text}) => {
      return getCodeName(designTypeList.value, text);
    }
  },
  {
    title: "模板名称",
    dataIndex: "name",
    align: "center"
  },
  {
    title: "创建时间",
    dataIndex: "createdTime",
    align: "center"
  },
  {
    title: "创建人",
    dataIndex: "createdUserName",
    align: "center"
  },
  {
    title: "状态",
    dataIndex: "isEnable",
    align: "center",
    customRender({text}) {
      if (text) return "已启用";
      return "已禁用";
    }
  },
  {
    title: "操作",
    dataIndex: "handle",
    align: "center",
    width: 120,
    fixed: "right"
  }
];
</script>

<style lang="less" scoped></style>
